
class AuroraScreen {
  /**
   * 屏幕号
   * @type {String}
   */
  sid = null;
  /**
   * @type {String}
   */
  series = null;
  /**
   * @type {String}
   */
  scene = null;
  /**
   * 初始加载的 JS 代码路径
   * @type {String}
   */
  try = null;
  /**
   * 展示屏的别名
   * @type {String}
   */
  name = null;
  /**
   * 初始化选项.
   * 该参数是放在 url 里面的 param 中, key='p'
   */
  initParam = '';

  valid = function() {
    return ((this.sid) && (this.series) && (this.scene) && (this.entry));
  };
  
  sceneFullName = function() {
    return `${this.series}/${this.scene}`;
  }
}

function extractContent() {
  let array = document.head.getElementsByTagName('meta');
  let obj = new AuroraScreen();

  for (let key in array) {
    let meta = array[key];
    switch (meta.name) {
      case 'aurora-screen':
        obj.sid = meta.content;
        break;
      case 'aurora-scene':
        let index = meta.content.indexOf('/');
        obj.series = meta.content.substring(0, index);
        obj.scene = meta.content.substring(index + 1);
        break;
      case 'aurora-entry':
        obj.entry = meta.content;
        break;
      case 'aurora-screen-alias':
        obj.name = meta.content;
        break;
    }
  }

  let searchs = parseUrlSearchParam();
  if (searchs.p) {
    obj.initParam = searchs.p instanceof Array ? searchs.p.join(' ') : searchs.p;
  }

  if (!obj.valid()) {
    throw obj;
  }

  return obj;
}

function parseUrlSearchParam() {
  let searchs = location.search.split('&');
  let param = {};
  for (let i = 0; i < searchs.length; i++) {
    let pair = searchs[i].split('=');
    let key = decodeURIComponent(pair[0]);
    let value = decodeURIComponent(pair[1]);
    if (!param[key]) {
      param[key] = value;
      continue;
    }
    if (param[key] instanceof Array) {
      param[key].push(value);
      continue;
    }
    param[key] = [ param[key], value ];
  }
  return param;
}

export default extractContent;
